package com.tg.login.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.Window;
import android.widget.Button;

import androidx.annotation.Nullable;

import com.base.BaseActivity;
import com.tange.base.toolkit.StatusBarUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.DialogUtil;
import com.tg.appcommon.android.FontUtil;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.router.TGBusiness;
import com.tg.data.http.entity.LoginBean;
import com.tg.login.R;
import com.tg.login.view.TGEditText;
import com.tg.loginex.helper.LoginHelper;

public class SetPasswordActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = SetPasswordActivity.class.getSimpleName();
    private String account, code;
    private Button finish;
    private TGEditText edtNewpassword, edtRepassword;

    private boolean isForget;
    private boolean isCheckBox = false;
    private String startType;
    private static final int MIN_LEN = 8;
    private static final int LOCK_BELL_MIN_LEN = 6;
    private int minLen = MIN_LEN;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_setpwd_register);
        Intent intent = getIntent();
        hideActionBar();
        StatusBarUtil.setStatusBarTransparent(this);
        startType = getIntent().getStringExtra(LoginHelper.START_TYPE);
        account = intent.getStringExtra("account");
        code = intent.getStringExtra("code");
        isForget = intent.getBooleanExtra("isForget", false);
        initView();
        initData();
    }

    private void setClickBackImpl(){
        if (StringUtils.equalsIgnoreCase(LoginHelper.LOCK_BELL_SETTING_PASSWORD, startType)){
            finish();
        }else{
            DialogUtil.openDlalog(SetPasswordActivity.this, getString(R.string.register_dialog_tile),
                    null,
                    getString(R.string.confirm),
                    getString(R.string.dialog_cancel), v1 -> finish(), v12 -> {

                    }, ResourcesUtil.getResources().getColor(R.color.drive_btn_record_selected));
        }

    }
    @Override
    protected void initView() {
        setClickBack(v -> setClickBackImpl());
        finish = findViewById(R.id.login);
        edtNewpassword = findViewById(R.id.editText);
        edtRepassword = findViewById(R.id.editText2);

        edtNewpassword.setTypeface(FontUtil.getMedium());
        edtRepassword.setTypeface(FontUtil.getMedium());

        edtRepassword.setCheckBoxClickListener(v -> checkBoxClick());

        if (StringUtils.equalsIgnoreCase(LoginHelper.LOCK_BELL_SETTING_PASSWORD, startType)){
            minLen = LOCK_BELL_MIN_LEN;
            edtNewpassword.setHint(R.string.txt_input_num6);
            edtNewpassword.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
            edtRepassword.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
            edtNewpassword.setLetterOrDigitFilterSymbolsLength(MIN_LEN);
            edtRepassword.setLetterOrDigitFilterSymbolsLength(MIN_LEN);
            edtNewpassword.setOnFocusChangeListener((v, hasFocus) -> {
                if (hasFocus){
                    String text = edtNewpassword.getText();
                }
            });
            edtNewpassword.setOnClickListener(view -> {
                String text = edtNewpassword.getText();

            });
        }else{
            edtNewpassword.setLetterOrDigitFilterSymbolsLength();
            edtRepassword.setLetterOrDigitFilterSymbolsLength();
        }

        finish.setOnClickListener(this);
        setFinishBtnEnabled();
        edtNewpassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                String text1 = edtRepassword.getText();
                TGLog.d(TAG, "s = " + s + ",.text = " + text1);
                edtNewpassword.setImageVisibility(s.length() >= minLen? View.VISIBLE : View.GONE);
                if (StringUtils.isEmpty(s) && StringUtils.isEmpty(text1)){
                    edtNewpassword.setImageVisibility(View.GONE);
                    edtRepassword.setImageVisibility(View.GONE);
                    setFinishBtnEnabled();
                    return;
                }
                if (s.length() >= minLen){
                    edtNewpassword.setImageResource(R.mipmap.right);
                    edtNewpassword.setImageVisibility(View.VISIBLE);
                    if (s.equals(text1)){
                        edtRepassword.setImageResource(R.mipmap.right);
                    }else{
                        edtRepassword.setImageResource(R.mipmap.error);
                    }
                    edtRepassword.setImageVisibility(View.VISIBLE);
                    setFinishBtnEnabled();
                    return;
                }

                if (!StringUtils.isEmpty(text1)){
                    edtRepassword.setImageResource(R.mipmap.error);
                }
                setFinishBtnEnabled();
            }
        });

        edtRepassword.setOnFocusChangeListener((v, hasFocus) -> {
            TGLog.d(TAG, "hasFocus = " + hasFocus);
            if (hasFocus) {
                if (StringUtils.equalsIgnoreCase(LoginHelper.LOCK_BELL_SETTING_PASSWORD, startType)){
                    String text = edtRepassword.getText();
                }
                String text1 = edtNewpassword.getText();
                String text2 = edtRepassword.getText();
                if (text1.length() < minLen){
                    edtNewpassword.setImageResource(R.mipmap.error);
                    edtNewpassword.setImageVisibility(View.VISIBLE);
                }

                if (!text2.equals(text1)){
                    edtRepassword.setImageResource(R.mipmap.error);
                    edtRepassword.setImageVisibility(View.VISIBLE);
                }
            }
        });

        if (StringUtils.equalsIgnoreCase(LoginHelper.LOCK_BELL_SETTING_PASSWORD, startType)){
            edtRepassword.setOnClickListener(view -> {
                String text = edtRepassword.getText();
            });
        }
        edtRepassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                String text1 = edtNewpassword.getText();

                TGLog.d(TAG, "s = " + s + ",.text = " + text1);
                if (text1.length() < minLen){
                    edtNewpassword.setImageResource(R.mipmap.error);
                }
                if (StringUtils.isEmpty(s) && StringUtils.isEmpty(text1)){
                    edtNewpassword.setImageVisibility(View.GONE);
                    edtRepassword.setImageVisibility(View.GONE);
                    setFinishBtnEnabled();
                    return;
                }

                edtNewpassword.setImageVisibility(View.VISIBLE);
                edtRepassword.setImageVisibility(View.VISIBLE);
                if (text1.length() < minLen){
                    edtNewpassword.setImageResource(R.mipmap.error);
                }else if (text1.equals(s)){
                    edtNewpassword.setImageResource(R.mipmap.right);
                    edtRepassword.setImageResource(R.mipmap.right);
                }else {
                    edtRepassword.setImageResource(R.mipmap.error);
                }
                if (s.length() < minLen){
                    edtRepassword.setImageResource(R.mipmap.error);
                }

                setFinishBtnEnabled();
            }
        });
        edtNewpassword.setImageVisibility(View.GONE);
        edtRepassword.setImageVisibility(View.GONE);
    }
    private void setFinishBtnEnabled(){
        String newPwd = edtNewpassword.getText().trim();
        String oldPwd = edtRepassword.getText().trim();
        if (!TextUtils.isEmpty(newPwd)&&!TextUtils.isEmpty(oldPwd)){
            if (newPwd.length() >= minLen && oldPwd.length() >= minLen && newPwd.equals(oldPwd)) {
                LoginHelper.setButtonEnable(finish, true);
                return;
            }
        }
        LoginHelper.setButtonEnable(finish, false);
    }

    private void initData(){
        edtRepassword.setText("");
        edtNewpassword.setText("");
        setFinishBtnEnabled();
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.login || id == R.id.button_with_text) {
            String password = edtNewpassword.getText().trim();
            if (!StringUtils.isEnOrNum(password)) {
                TGToast.showToast(R.string.pwd_isenandnum);
                return;
            }
            if (isForget){
                reset(account, password, code, LoginHelper.PHONE_CODE);
            }else{
                register(account, password, code, LoginHelper.PHONE_CODE, LanguageUtils.getCountry(this));
            }
        }
    }

    private void checkBoxClick() {
        isCheckBox = !isCheckBox;
        TGLog.d(TAG + "-log", "isCheckBox =" + isCheckBox);
        edtRepassword.getCheckBox().setBackgroundResource(isCheckBox ? R.drawable.ic_tange_global_icon_password_visible : R.drawable.ic_tange_global_icon_password_invisible);
        if (isCheckBox) {
            edtNewpassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            edtRepassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            edtNewpassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            edtRepassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        if (edtNewpassword.getText().trim().length() > 0) {
            edtNewpassword.setSelection(edtNewpassword.getText().trim().length());
        }
        if (edtRepassword.getText().trim().length() > 0) {
            edtRepassword.setSelection(edtRepassword.getText().trim().length());
        }
    }



    private void register(String userName, String password, String code, String phoneAreaCode, String countryCode){
        LoginHelper.register(userName, code, password, phoneAreaCode, countryCode, new LoginHelper.LoginListener<LoginBean>() {
            @Override
            public void onSuccess(LoginBean content) {
                TGToast.showToast(R.string.register_success);
                TGBusiness.getAppModule().startLoginActivity(SetPasswordActivity.this, null);
                finish();
            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                showToast(errorInfo);
            }

            @Override
            public void onFinish() {
                hideLoading();
            }
        });
    }

    private void reset(String userName, String password, String code, String phoneAreaCode){
        LoginHelper.reset(userName, code, password, phoneAreaCode, new LoginHelper.LoginListener<LoginBean>() {
            @Override
            public void onSuccess(LoginBean content) {
                TGToast.showToast(R.string.txt_password_success);
                TGBusiness.getAppModule().startLoginActivity(SetPasswordActivity.this,  null);
                finish();
            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                showToast(errorInfo);
            }

            @Override
            public void onFinish() {
                hideLoading();
            }
        });
    }
}
